package user;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import fj.F;
import global.Global;

import search.SaveSearch;
import server.db.DatabaseFunctor;
import server.db.StmtHelper;
import util.Validation;

import ajaxmethods.AjaxMethod;

public class SubmitLogin implements AjaxMethod {

	private List<String> requiredFields = Arrays.asList("email","password");
	private Map<String,String> fieldsMap = new HashMap();
	private JSONArray errors = new JSONArray();
	
	
	@Override
	public void perform(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/json");
		String fields = request.getParameter("fields");

		for(String field : fields.split(","))
		{
			String[] fvPair = field.split(":");
			if(fvPair.length>1)
			{
				fieldsMap.put(fvPair[0],fvPair[1]);
			}
		}
		validate();
		Global global = new Global(request);
		if(errors.length()<1 && !global.login(fieldsMap.get("email"),fieldsMap.get("password"),true))
		{
			addError("","email");
			addError("The email or password you entered is incorrect.","password");
		}
		JSONObject redirectObj = new JSONObject();
		if(errors.length() < 1)
		{
			
			//build success object	
			StringBuffer sb = new StringBuffer();
			if(fieldsMap.containsKey("redirect") && fieldsMap.get("redirect").equals("savesearch"))
			{
				sb=SaveSearch.getSaveSearchDlg();
				try {
					redirectObj = new JSONObject().put("redirect", sb.toString());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
			try {
				JSONObject returnobj = new JSONObject();
				if(global.getUser()!=null)
					returnobj = global.getUser().toJson();
				returnobj.put("submitlogin",redirectObj);
				if(errors.length()>0)
					returnobj.put("errors", errors);
				returnobj.write(response.getWriter());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
	}

	private void validate() {
		//check requiredness
		for(String fieldName : requiredFields)
		{
			if(fieldsMap.get(fieldName)==null ||"".equals(fieldsMap.get(fieldName)))
				addError("required",fieldName);
		}
		if(errors.length()<1)
		{
			//validate email address
			if(!Validation.isValidEmailAddress(fieldsMap.get("email")))
			{
				addError("Not a valid email address","email");
			}
		}
	}

	private void addError(String errortype, String fieldName) {
		JSONObject error;
		try {
			error = new JSONObject().put("error", errortype).put("fieldname",fieldName);
			errors.put(error);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
